package com.banksoft.admin.controller;

import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.bean.Status;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.entity.UserAddress;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.OrderService;
import com.banksoft.admin.service.UserAddressService;
import com.banksoft.admin.service.UserService;
import com.banksoft.common.BaseController;
import com.banksoft.common.PageInfo;
import com.banksoft.front.bean.OrderCompare;
import com.banksoft.front.bean.UserCompare;
import com.banksoft.util.DateUtil;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Member;
import java.util.*;

/**
 * Created by vanjoger on 2016/12/28.
 */
@Controller
@RequestMapping("/member")
public class MemberController extends BaseController {

    @Autowired
    BaseService baseService;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    UserAddressService userAddressService;

    @RequestMapping("/list")
    public String list(String type,Model model){
        model.addAttribute("type",type);
        return "member/member_list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public Object listData(String nickName,String type,String account,String userName,String status,PageInfo pageInfo){
        Map<String,Object> map = new HashMap<>();
        String[] types = null;
        if(!StringUtil.isNotNull(type)){
            //type = "('"+ MemberType.Glod.name()+"','"+MemberType.General.name()+"','"+MemberType.Partner.name()+"')";
            types = new String[]{MemberType.Gold.name(),MemberType.General.name(),MemberType.Partner.name()};
        }else{
            //type = "('"+type+"')";
            if(MemberType.Partner.name().equals(type)){
                map.put("isPartner","1");
                types = new String[]{MemberType.General.name()};
            }else{
                types = new String[]{type};
            }
        }
        map.put("isMember","1");
        map.put("account",account);
        map.put("type",types);
        map.put("userName",userName);
        map.put("status",status);
        if(StringUtil.isNotNull(nickName))
            map.put("nickName",nickName);

        pageInfo.setParams(map);

        pageInfo = this.page(UserDao.class,pageInfo);
        List<User> list = pageInfo.getResult();
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                List<UserAddress> addressList = userAddressService.listByUserId(user.getId());
                if(StringUtil.isNotEmpty(addressList)){
                    UserAddress address = addressList.get(0);
                    user.setCardName(address.getUserName());
                    if(!StringUtil.isNotNull(user.getMobile())){
                        user.setMobile(address.getTelephone());
                    }else{
                        user.setMobile(user.getMobile()+"/"+address.getTelephone());
                    }
                }
                if(StringUtil.isNotNull(user.getRecommendId())) {
                    User upuser = baseService.findById(UserDao.class,user.getRecommendId());
                    if(upuser!=null){
                        if(StringUtil.isNotNull(upuser.getCardName())){
                            user.setRecommendId(upuser.getCardName());
                        }else{
                            List<UserAddress> upuserAddressList = userAddressService.listByUserId(upuser.getId());
                            if(StringUtil.isNotEmpty(upuserAddressList)){
                                UserAddress address = upuserAddressList.get(0);
                                user.setRecommendId(address.getUserName());
                            }else{
                                user.setRecommendId(upuser.getNickName()+"("+upuser.getAccount()+")");
                            }
                        }
                    }else{
                        user.setRecommendId("");
                    }
                }
                List<User> subList = this.userService.listByRecommendId(user.getId());
                user.setSubSize(subList!=null?subList.size():0);
            }
        }
        pageInfo.setResult(list);

        return this.getPageResult(pageInfo);
    }



    @RequestMapping("/listTeam")
    public String listTeam(String id,String level,Model model){
        model.addAttribute("id",id);
        model.addAttribute("level",(Integer.parseInt(level)+1));

        Map map = getTdyj(id);
        model.addAttribute("orders",map.get("orders"));
        model.addAttribute("tdyj",map.get("tdyj"));

        return "member/member_team_list";
    }

    /**
     * 读取团队业绩
     * @param id
     * @return
     */
    private Map<String,String> getTdyj(String id){
        Map map = new HashMap();
        List<User> userlist = this.userService.listByRecommendId(id);
        String ids = "";
        if(StringUtil.isNotEmpty(userlist)){
            for(User user:userlist){
                ids += user.getId()+",";
            }
        }
        if(ids.length()>0)
            ids = ids.substring(0,ids.length()-1);
        List<Order> orderlist = this.orderService.listByUserIds(ids.split(","));
        String totalMoney = "0";
        if(StringUtil.isNotEmpty(orderlist)){
            for(Order order:orderlist){
                totalMoney = StringNumber.add(totalMoney,order.getTotalMoney());
            }
        }
        map.put("subsize",userlist!=null?userlist.size():0);
        map.put("orders",orderlist!=null?orderlist.size():0);
        map.put("tdyj",totalMoney);
        return map;
    }


    @RequestMapping("/listTeamData")
    @ResponseBody
    public Object listTeamData(String id,PageInfo pageInfo){
        Map<String,Object> map = new HashMap<>();

        map.put("recommendId",id);
        map.put("isMember","1");

        pageInfo.setParams(map);

        pageInfo = this.page(UserDao.class,pageInfo);
        List<User> list = pageInfo.getResult();
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                Map data = getTdyj(user.getId());
                List<UserAddress> addressList = userAddressService.listByUserId(user.getId());
                if(StringUtil.isNotEmpty(addressList)){
                    UserAddress address = addressList.get(0);
                    if(!StringUtil.isNotNull(user.getCardName()))
                        user.setCardName(address.getUserName());
                    if(!StringUtil.isNotNull(user.getMobile())){
                        user.setMobile(address.getTelephone());
                    }else{
                        user.setMobile(user.getMobile()+"/"+address.getTelephone());
                    }
                }
                user.setTdyj((String) data.get("tdyj"));
                user.setOrders((Integer) data.get("orders"));
                user.setSubSize((Integer) data.get("subsize"));
            }
        }
        pageInfo.setResult(list);

        return this.getPageResult(pageInfo);
    }

    @RequestMapping("/beforeEdit")
    public String beforeEdit(String id,Model model,String enter){
        if(StringUtil.isNotNull(id)){
            User user = this.baseService.findById(UserDao.class,id);
            if(user!=null){
                if(StringUtil.isNotNull(user.getRecommendId())) {
                    User upuser = baseService.findById(UserDao.class,user.getRecommendId());
                    if(upuser!=null){
                        if(StringUtil.isNotNull(upuser.getCardName())){
                            user.setTdyj(upuser.getCardName()+"("+upuser.getAccount()+")");
                        }else{
                            List<UserAddress> upuserAddressList = userAddressService.listByUserId(upuser.getId());
                            if(StringUtil.isNotEmpty(upuserAddressList)){
                                UserAddress address = upuserAddressList.get(0);
                                user.setTdyj(address.getUserName()+"("+upuser.getAccount()+")");
                            }else{
                                user.setTdyj(upuser.getNickName()+"("+upuser.getAccount()+")");
                            }
                        }
                    }
                }
                //查找收货地址
                List<UserAddress> list = this.userAddressService.listByUserId(id);
                UserAddress address = null;
                String addressStr = "";
                if(StringUtil.isNotEmpty(list)){
                    address = list.get(0);
                    addressStr = address.getAddress();
                }
                String mobile = user.getMobile();
                String userName = user.getCardName();
                String province = user.getUserProvince();
                String city = user.getUserCity();
                String area = user.getUserArea();

                if(!StringUtil.isNotNull(mobile)){
                   if(address!=null)
                       mobile = address.getTelephone();
                }
                if(!StringUtil.isNotNull(province)){
                    if(address!=null)
                        province = address.getProvince();
                }
                if(!StringUtil.isNotNull(city)){
                    if(address!=null)
                        city = address.getCity();
                }
                if(!StringUtil.isNotNull(area)){
                    if(address!=null)
                        area = address.getArea();
                }
                if(!StringUtil.isNotNull(userName)){
                    if(address!=null)
                        userName = address.getUserName();
                }
                model.addAttribute("address",addressStr);
                model.addAttribute("mobile",mobile);
                model.addAttribute("userName",userName);
                model.addAttribute("province",province);
                model.addAttribute("city",city);
                model.addAttribute("area",area);
                model.addAttribute("data",user);
            }
        }
        model.addAttribute("enter",enter);
        return "member/member_edit";
    }

    @RequestMapping("/save")
    @ResponseBody
    public JSONObject save(User user,HttpServletRequest request,String address){
        try{
            if(user.getType().equals(MemberType.Partner.name())) {
                List<User> list = userService.listUserByCity(user.getUserLevel(), user.getUserProvince(), user.getUserCity(), user.getUserArea());
                if (StringUtil.isNotEmpty(list)) {
                    User puser = list.get(0);
                    if(!puser.getId().equals(user.getId()))
                        return this.FmtResult(false,"该区域已有其他的区域合伙人，请重新选择",null);
                }
            }

            userService.update(user,address);

            this.saveLog("更新用户信息："+JSONObject.fromObject(user),request);
            return this.FmtResult(true,"保存成功",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"保存失败",null);
    }

    @RequestMapping("/updateStatus")
    @ResponseBody
    public JSONObject updateStatus(String id, String status, HttpServletRequest request){
        try{
            User user = this.baseService.findById(UserDao.class,id);
            if(user!=null){
                user.setStatus(status);
                this.baseService.update(UserDao.class,user);
                if(status.equals(Status.NORMAL.name())) {
                    this.saveLog("启用代理商",request);
                }else if(status.equals(Status.FROZEN.name())){
                    this.saveLog("冻结代理商",request);
                }
                return this.FmtResult(true,"操作成功",null);
            }
            return this.FmtResult(false,"没有找到数据",null);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"操作失败",null);
    }

    @RequestMapping("/xq")
    @ResponseBody
    public JSONObject xq(String id){
        try{
            User user = this.baseService.findById(UserDao.class,id);
            if(user!=null){
                if((user.getType().equals(MemberType.General.name())&&"1".equals(user.getIsPartner()))||(user.getType().equals(MemberType.Partner.name()))){
                    user.setType(MemberType.General.name());
                    user.setIsPartner("1");
                    user.setPartnerDate(new Date().getTime());
                    this.baseService.update(UserDao.class,user);
                    return this.FmtResult(true,"续签成功",null);
                }
                return this.FmtResult(false,"当前用户不是区域合伙人，无法续签",null);
            }
            return this.FmtResult(false,"没有找到数据",null);
        }catch (Exception e){
            e.printStackTrace();
            return this.FmtResult(false,"操作失败",null);
        }
    }

    @RequestMapping("/memberCnt")
    @ResponseBody
    public JSONObject memberCnt(String id){
        try {
            List<User> list = this.userService.listByRecommendId(id);
            Map map = new HashMap();
            int userTotal = 0;
            int userCnt = 0;
            int goldCnt = 0;
            int generalCnt = 0;
            int partnerCnt = 0;

            if(StringUtil.isNotEmpty(list)){
                for(User user:list){
                    if(user.getType().equals(MemberType.Gold.name())){
                        goldCnt ++;
                    }else if(user.getType().equals(MemberType.General.name())&&(!"1".equals(user.getIsPartner()))){
                        generalCnt++;
                    }else if(user.getType().equals(MemberType.General.name())&&("1".equals(user.getIsPartner()))){
                        partnerCnt++;
                    }else{
                        userCnt++;
                    }
                }
                userTotal = list.size();
            }
            map.put("userTotal",userTotal);
            map.put("userCnt",userCnt);
            map.put("goldCnt",goldCnt);
            map.put("generalCnt",generalCnt);
            map.put("partnerCnt",partnerCnt);
            return this.FmtResult(true,null,map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

    /**
     * 团队业绩
     */
    @RequestMapping("/listTeamYj")
    public String listTeamYj(String id,Model model){
        model.addAttribute("id",id);
        return "/member/member_team_yj";
    }

    @RequestMapping("/loadTeamYjData")
    @ResponseBody
    public JSONObject loadTeamYjData(String id){
        try {
            List<User> userlist = new ArrayList<>();
            List<Order> orderlist = new ArrayList<>();
            getAllUserAndOrder(id,userlist,orderlist);

            int userTotal = userlist!=null?userlist.size():0;
            int userCnt = 0;
            int generalCnt = 0;
            int partnerCnt = 0;
            int goldCnt = 0;

            if(StringUtil.isNotEmpty(userlist)){
                for(User user:userlist){
                    if(user.getType().equals(MemberType.Gold.name())){
                        goldCnt ++;
                    }else if(user.getType().equals(MemberType.General.name())&&(!"1".equals(user.getIsPartner()))){
                        generalCnt++;
                    }else if(user.getType().equals(MemberType.General.name())&&("1".equals(user.getIsPartner()))){
                        partnerCnt++;
                    }else{
                        userCnt++;
                    }
                }
            }

            String totalMoney = "0";
            int orderCnt = orderlist!=null?orderlist.size():0;
            int gworder = 0;
            int sjorder = 0;
            int payorder = 0;
            int sendorder = 0;
            if(StringUtil.isNotEmpty(orderlist)){
                for(Order order:orderlist){
                    if("0".equals(order.getType())){
                        gworder++;
                        if(OrderStatus.Pay.name().equals(order.getStatus())){
                            payorder++;
                        }else if(OrderStatus.Send.name().equals(order.getStatus())){
                            sendorder++;
                        }
                    }else if("1".equals(order.getType())){
                        sjorder++;
                    }
                    totalMoney = StringNumber.add(totalMoney,order.getTotalMoney());
                }
            }

            Map map = new HashMap();
            map.put("memberCnt",userTotal);
            map.put("userCnt",userCnt);
            map.put("generalCnt",generalCnt);
            map.put("partnerCnt",partnerCnt);
            map.put("goldCnt",goldCnt);
            map.put("orderCnt",orderCnt);
            map.put("gwOrderCnt",gworder);
            map.put("sjOrderCnt",sjorder);
            map.put("yjTotal",totalMoney);

            return this.FmtResult(true,null,map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,null,null);
    }

    /**
     * 得到所有的用户和订单
     * @param id
     * @param userlist
     */
    private void getAllUserAndOrder(String id, List<User> userlist, List<Order> orderlist) {
        List<User> list = this.userService.listByRecommendId(id);
        List<Order> orders = orderService.listByUserIds(new String[]{id});
        if(StringUtil.isNotEmpty(orders))
            orderlist.addAll(orders);
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                if(!user.getId().equals(id)){
                    userlist.add(user);
                    getAllUserAndOrder(user.getId(),userlist,orderlist);
                }
            }
        }
    }

    @RequestMapping("/teamMember")
    public String teamMember(String id,String index,Model model){
        model.addAttribute("id",id);
        model.addAttribute("index",index);
        return "member/team_member_list";
    }

    /**
     * 得到所有的用户和订单
     * @param id
     * @param userlist
     */
    private void getAllUser(String id, List<User> userlist) {
        List<User> list = this.userService.listByRecommendId(id);

        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                if(!user.getId().equals(id)){
                    userlist.add(user);
                    getAllUser(user.getId(),userlist);
                }
            }
        }
    }

    /**
     * 得到所有的用户和订单
     * @param id
     */
    private void getAllOrder(String id,  List<Order> orderlist) {
        List<User> list = this.userService.listByRecommendId(id);
        List<Order> orders = orderService.listByUserIds(new String[]{id});
        if(StringUtil.isNotEmpty(orders))
            orderlist.addAll(orders);
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                if(!user.getId().equals(id)){
                    getAllOrder(user.getId(),orderlist);
                }
            }
        }
    }


    @RequestMapping("/teamMemberData")
    @ResponseBody
    public JSONObject teamMemberData(String id,String index,PageInfo pageInfo){

        List<User> userlist = new ArrayList<>();
        getAllUser(id,userlist);
        List<User> data = new ArrayList<>();
        if(StringUtil.isNotEmpty(userlist)){
            for(User user:userlist){
                if(!StringUtil.isNotNull(user.getCardName()))
                    user.setCardName(user.getNickName());
                if("1".equals(index)){
                    if(MemberType.Customer.name().equals(user.getType()))
                        data.add(user);
                }else if("2".equals(index)){
                    if(MemberType.Gold.name().equals(user.getType()))
                        data.add(user);
                }else if("3".equals(index)){
                    if(MemberType.General.name().equals(user.getType())&&!"1".equals(user.getIsPartner()))
                        data.add(user);
                }else if("4".equals(index)){
                    if(MemberType.General.name().equals(user.getType())&&"1".equals(user.getIsPartner()))
                        data.add(user);
                }else {
                    data.add(user);
                }
            }
        }
        UserCompare compare = new UserCompare();
        Collections.sort(userlist,compare);

        int start = pageInfo.getStart();
        int limit = pageInfo.getLimit();
        int end = start+limit;
        if(end>data.size())
            end = data.size();
        List<User> users = data.subList(start,end);
        pageInfo.setResult(users);
        pageInfo.setTotal(data.size());
        return this.getPageResult(pageInfo);
    }


    @RequestMapping("/teamOrder")
    public String teamOrder(String id,String index,Model model){
        model.addAttribute("id",id);
        model.addAttribute("index",index);
        return "member/team_order_list";
    }

    @RequestMapping("/teamOrderData")
    @ResponseBody
    public JSONObject teamOrderData(String id,String index,PageInfo pageInfo){
        List<Order> orderlist = new ArrayList<>();
        getAllOrder(id,orderlist);
        List<Order> data = new ArrayList<>();
        if(StringUtil.isNotEmpty(orderlist)){
            for(Order order:orderlist){
                if("1".equals(index)){
                    if("1".equals(order.getType()))
                        data.add(order);
                }else if("0".equals(index)){
                    if("0".equals(order.getType()))
                        data.add(order);
                }else if("2".equals(index)){
                    data.add(order);
                }
            }
        }
        OrderCompare compare = new OrderCompare();
        Collections.sort(orderlist,compare);

        int start = pageInfo.getStart();
        int limit = pageInfo.getLimit();
        int end = start+limit;
        if(end>data.size())
            end = data.size();
        List<Order> users = data.subList(start,end);
        pageInfo.setResult(users);
        pageInfo.setTotal(data.size());
        return this.getPageResult(pageInfo);
    }


}
